<template>
  <md-page title="上传图片打卡" isBtn :btnTextItems="data.btnTextItems" @btnClick="debouncedHandleBottomBtnClick">
    <view class="container">
      <view class="card m-bottom-20">
        <view class="title m-bottom-12">{{ data.info?.point_name || '' }}</view>
        <view v-if="data.info?.point_type?.length > 0" class="tags m-bottom-30">
          <view v-for="item in data.info?.point_type" :key="item" :class="['tag', data.tagMap[item]]">
            {{ data.pointType[item] }}
          </view>
        </view>
        <!-- 补给处理 1：未核销 2：已核销 -->
        <block v-if="data.info?.is_check_bg == 1">
          <!-- 补给二维码 -->
          <view class="buji-wrap m-bottom-30" @click="handleOpen" v-if="data.info?.point_type?.includes('3')">
            <view class="left-title">补给券</view>
            <view class="content">点击扫描补给券二维码</view>
            <view class="code">
              <md-icon name="code" width="77" height="77"></md-icon>
            </view>
          </view>
        </block>
        <view class="buji-wrap m-bottom-30" v-else>
          <view class="left-title">核销状态</view>
          <view class="content">已核销</view>
        </view>
        <view class="image-wrap">
          <view class="left-title">拍照样例图</view>
          <view class="content">
            <image
              class="img"
              v-for="(item, index) in data.info.imgData"
              :src="item"
              :key="item"
              @click="() => handlePreview(index)" />
          </view>
        </view>
      </view>
      <view class="card m-bottom-20">
        <view class="upload-wrap">
          <!-- <md-icon v-if="data.info?.check_img" :url="data.info?.check_img" width="150" height="150" /> -->
          <uni-file-picker
            v-model="data.info.check_img"
            title="拍照上传图片"
            return-type="object"
            file-mediatype="image"
            :imageStyles="{ width: '150rpx', height: '150rpx' }"
            @select="handleUpload"></uni-file-picker>
          <view v-if="data.info?.check_status == 4" class="desc m-top-20">
            ({{ data.info?.fail_reason ? '审核' : '自动识别' }}未通过您可{{
              data.info?.fail_reason ? '查看驳回理由，再次' : '选择'
            }}人工审核)
          </view>
          <view v-if="data.info?.fail_reason" class="desc m-top-20">驳回理由: {{ data.info?.fail_reason }}</view>
        </view>
      </view>
      <view class="red m-bottom-20">*注：尽可能贴近样例图的角度进行拍照上传</view>
      <view v-if="data.info?.check_status == 3" class="red fontW">
        (人工审核中，请在打卡点附近等待审核结果等待时间预计5分钟)
      </view>
      <!-- 核销二维码弹窗 -->
      <uni-popup ref="popup" type="center">
        <view class="pop_content flex-c">
          <ikun-qrcode width="390" height="390" unit="rpx" color="#000000" :data="bujiUrl" />
        </view>
      </uni-popup>
    </view>
  </md-page>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
// 接口
import {
  singleCompeteSubmitPicCheck,
  singleCompeteSubmitPicManualCheck,
  singleCompetePicPointInfo,
  uploadImage,
} from '@/api';
import { PointType } from '@/common/enum';
import type { BtnTextItem } from '@/components/md-ui/components/md-page/md-page.vue';
// 工具
import { debounce } from 'lodash';

const data = reactive<any>({
  point_id: '',
  btnTextItems: [],
  pointType: PointType,
  tagMap: {
    '1': 'daka',
    '2': 'zhuti',
    '3': 'buji',
    '4': 'daka',
    '5': 'zhuti',
    '6': 'buji',
    '7': 'daka',
  },
  info: {},
  url: '',
  loading: false,
});
const bujiUrl = ref<string>('');
const popup = ref(null);

const handleOpen = () => {
  popup.value?.open?.();
};

// 图片预览
const handlePreview = (current: number) => {
  if (data.info?.imgData?.length == 0) return;
  uni.previewImage({
    urls: data.info?.imgData,
    current,
  });
};

const bottomBtnClick = async (info: { item: BtnTextItem }) => {
  if (data.loading) return; // 等待异步结果才能继续点击
  const { key } = info.item;
  // 提交人工审核
  if (key === 'service') {
    fetchMatchSubmitPicManualCheck({ img: data.url, point_id: data.point_id });
  } else {
    // 提交
    fetchMatchSubmitPicCheck({ img: data.url, point_id: data.point_id });
  }
};

// 使用 debounce 包装 bottomBtnClick 函数
const debouncedHandleBottomBtnClick = debounce(bottomBtnClick, 300);

/**
 * 接口相关
 */
// 当前点位信息
const fetchMatchUploadImgCheck = async (point_id?: string) => {
  try {
    const res = await singleCompetePicPointInfo({
      point_id: point_id || data.point_id,
    });
    // 补给二维码生成
    // 补给点 3
    if (res.data?.is_check_bg == 1 && res.data?.point_type?.includes('3')) {
      bujiUrl.value = `/pages/other/scanCode/index?signid=${res.data?.sign_id}&pointid=${res.data?.point_id}&type=2&end=`;
    }
    // 按钮处理
    data.btnTextItems = [
      { text: '提交人工审核', key: 'service', color: '#1CA4C0', hide: res.data?.check_status != 4 },
      { text: '提交', key: 'submit', hide: res.data?.check_status != 1 },
    ];
    // 图片处理
    let _check_img = res.data?.check_img
      ? {
          url: res.data.check_img,
          extname: 'png',
          name: 'checkUploadPic.png',
        }
      : undefined;
    data.url = res.data?.check_img;
    data.info = {
      ...res.data,
      check_img: _check_img,
    };
  } catch (error) {}
};

// 上传图片
const handleUpload = (e: any) => {
  // console.log('选择文件：', e);
  let { tempFilePaths } = e;
  uni.showLoading({
    title: '图片上传中...',
    mask: true,
  });
  uploadImage({ filePath: tempFilePaths[0], formData: { category: 'sign', active_id: data.point_id } }).then(
    async res => {
      data.url = res?.data?.url;
      uni.hideLoading();
    }
  );
};

// 提交图片校验
const fetchMatchSubmitPicCheck = async (params: { point_id: string; img: string }) => {
  data.loading = true;
  try {
    const res = await singleCompeteSubmitPicCheck(params);
    uni.showModal({
      title: '提示',
      content: res?.msg || '提交成功',
      showCancel: false,
      success: res => {
        if (res.confirm) {
          uni.navigateBack();
        }
      },
    });
  } catch (error) {
    fetchMatchUploadImgCheck();
  }
  data.loading = false;
};

// 上传图片人工打卡
const fetchMatchSubmitPicManualCheck = async (params: { point_id: string; img: string }) => {
  data.loading = true;
  try {
    const res = await singleCompeteSubmitPicManualCheck(params);
    uni.showModal({
      title: '提示',
      content: res?.msg || '提交成功',
      showCancel: false,
      success: res => {
        if (res.confirm) {
          uni.navigateBack();
        }
      },
    });
  } catch (error) {}
  data.loading = false;
};

onLoad(option => {
  data.point_id = option?.point_id;
  option?.point_id && fetchMatchUploadImgCheck(option?.point_id);
});
</script>

<style lang="scss" scoped>
.container {
  padding: 30rpx;
  box-sizing: border-box;
  font-size: 28rpx;
  & > .card {
    background: #ffffff;
    border-radius: 20rpx;
    padding: 20rpx;
    box-sizing: border-box;
    & > .title {
      font-weight: bold;
      font-size: 40rpx;
    }
    & > .tags {
      display: flex;
      align-items: center;
      gap: 20rpx;
      .tag {
        height: 40rpx;
        line-height: 40rpx;
        text-align: center;
        border-radius: 10rpx;
        padding: 0 18rpx;
        box-sizing: border-box;
        opacity: 0.9;
        color: white;
        &.zhuti {
          background: $primary;
        }
        &.daka {
          background: #eca342;
        }
        &.buji {
          background: #e64627;
        }
      }
    }
    .buji-wrap {
      width: 100%;
      background: #f7f7f7;
      border-radius: 20rpx;
      overflow: hidden;
      display: flex;
      align-items: center;
      & > .left-title {
        font-size: 34rpx;
        font-weight: bold;
        width: 80rpx;
        background: #1cc0b2;
        color: white;
        text-align: center;
        padding: 14rpx;
        box-sizing: border-box;
        height: 100%;
      }
      & > .content {
        flex: 1;
        font-size: 34rpx;
        font-weight: bold;
        text-align: center;
      }
      & > .code {
        margin: 0 30rpx;
      }
    }
    & > .image-wrap {
      display: flex;
      background: #f7f7f7;
      & > .left-title {
        font-size: 34rpx;
        font-weight: bold;
        padding: 14rpx;
        box-sizing: border-box;
        width: 80rpx;
        background: $primary;
        border-radius: 20rpx 0 0 20rpx;
        color: white;
        text-align: center;
        display: flex;
        align-items: center;
      }
      & > .content {
        flex: 1;
        padding: 20rpx;
        box-sizing: border-box;
        border-radius: 20rpx;
        gap: 30rpx;
        display: flex;
        flex-wrap: wrap;
        .img {
          width: 150rpx;
          height: 150rpx;
          background: white;
          border-radius: 20rpx;
        }
      }
    }
    & > .upload-wrap {
      .desc {
        color: #e4a842;
      }
    }
  }
  .red {
    color: $danger;
  }
  .fontW {
    font-weight: bolder;
  }
  .grey {
    color: $sub;
  }
}
</style>
